package pers.hl.library.common;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import pers.hl.library.auth.AuthException;
import sun.dc.path.PathException;

/**
 * 统一拦截异常
 *
 * 利用注解 传入需要处理的异常
 */

@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    private static final String ERROR_MESSAGE_FORMAT = "【错误类型】%s 【错误信息】%s";
    private static final String DEFAULT_ERROR_MESSAGE = "未知错误，详见服务端报错";
    /**
     * 是否打印堆栈信息
     */
    private boolean printStack = true;

    /**
     * 处理异常信息，也可以再写方法定义处理其他异常
     *
     * @param e 异常
     */
    @ExceptionHandler(Exception.class)
    public Response handleCommonException(Exception e) {
        // 默认错误码为500
        String errorCode = Const.HttpStatusCode.HttpStatus_500;
        String msg = e.getMessage();
        if (StringUtils.isEmpty(msg)) {
            msg = DEFAULT_ERROR_MESSAGE;
        }
        if (e instanceof AuthException) {
            errorCode = Const.HttpStatusCode.HttpStatus_401;
        } else if (e instanceof MissingServletRequestParameterException || e instanceof HttpMessageNotReadableException) {
            errorCode = Const.HttpStatusCode.HttpStatus_400;
        } else if (e instanceof PathException || e instanceof NoHandlerFoundException) {
            errorCode = Const.HttpStatusCode.HttpStatus_404;
            msg = "您请求的地址不存在";
            printStack = false;
        } else if (e.getClass().isAssignableFrom(CustomException.class)) {
            errorCode = ((CustomException) e).getErrorCode();
        } else if (e instanceof RuntimeException) {
            msg = "服务端异常";
        }
        if (Const.HttpStatusCode.HttpStatus_404.equals(errorCode)) {
            printStack = false;
        }
        String errorMessage = String.format(ERROR_MESSAGE_FORMAT, e.getClass().getSimpleName(), msg);
        if (printStack) {
            e.printStackTrace();
        }
        return Response.fail(errorCode, errorMessage);
    }


}